const http = require('http');
const fs = require('fs');
// const mysql = require('mysql')
const jwt = require('jsonwebtoken');

const token = jwt.sign({
    exp: Math.floor(Date.now() / 1000) + (60 * 60),
    data: 'foobar'
}, 'secret');
http.createServer((req, res) => {
    res.writeHead(200, { 'Content-type': 'text/plain', 'charset': 'utf-8' });
    if (req.url == '/login') {
        fs.readFile("./login.json", "utf-8", (err, data) => {
            console.log("有人请求服务器了", req.url);
            if (req.method.toLowerCase() == 'post') {
                // node处理post请求,会把请求拆分成一小段一小段的二进制数据
                //定义一个变量,用来接收所有二进制数据
                let allData = "";
                // 请求头监听数据传输，使用allData变量来接收回调函数里面的传来过来数据参数
                req.on('data', function (chunk) {
                    allData += chunk;
                })
                // 全部数据传输完毕,会调用一个事件
                req.on('end', function () {
                    const { username, password } = JSON.parse(allData)
                    const loginArr = JSON.parse(data)
                    console.log(loginArr);
                    const arr = loginArr.map((value) => {
                        if (username == value.admin && password == value.password1 && password == value.password2) {
                            return value.admin
                        }
                    })
                    if (arr.includes(username)) {
                        fs.readFile('./user.json', 'utf-8', (err, data) => {
                            if (data.includes(username)) {
                                let msg = `{"code":3,"message":"登录成功","Token":"${token}"}`;
                                res.end(msg);
                            } else {
                                let msg = `{"code":0,"message":"登录成功","Token":"${token}"}`;
                                const arruser = JSON.parse(data)
                                arruser.push(username)
                                const newArr = [...new Set(arruser)]
                                const str = JSON.stringify(newArr)
                                fs.writeFile('./user.json', str, 'utf-8', (err, data) => {

                                })
                                res.end(msg);
                            }
                        })
                    } else {
                        let msg1 = `{"code":1,"message":"登录失败"}`;
                        res.end(msg1)
                    }

                })
            }


        })
    }
    if (req.url == '/index') {
        if (req.method.toLowerCase() == 'post') {
            let allData = "";
            // 请求头监听数据传输，使用allData变量来接收回调函数里面的传来过来数据参数
            req.on('data', function (chunk) {
                allData += chunk;
            })
            req.on('end', function () {
                fs.readFile('./user.json', 'utf-8', (err, data) => {
                    const arr = JSON.parse(data)
                    const { user: item } = JSON.parse(allData)
                    console.log(item);
                    if (data.includes(item)) {
                        const result = [];
                        for (var i = 0; i < arr.length; i++) {
                            if (arr[i] != item) {
                                result.push(arr[i]);
                            }
                        }
                        const str = JSON.stringify(result)
                        // console.log(str);
                        fs.writeFile('./user.json', str, 'utf-8', function (err, data) {
                            res.end()
                        })
                    }
                })
            })
        }
    }
    if (req.url == '/enroll') {
        if (req.method.toLowerCase() == 'post') {
            let allData = "";
            // 请求头监听数据传输，使用allData变量来接收回调函数里面的传来过来数据参数
            req.on('data', function (chunk) {
                allData += chunk;
            })
            req.on('end', function () {
                fs.readFile('./login.json', 'utf-8', (err, data) => {
                    const { username, password1,password2 } = JSON.parse(allData)
                    arrList = JSON.parse(data)
                    const arr = arrList.map((value, index, array) => {
                        return value.admin
                    })
                    if (arr.includes(username)) {
                        let msg = `{"code":0,"message":"用户名已存在"}`;
                        res.end(msg);
                    } else if (password1 != password2) {
                        let msg1 = `{"code":1,"message":"两次输入密码不一致"}`
                        res.end(msg1);
                    } else {
                        let msg2 = `{"code":2,"message":"注册成功请登录"}`
                        res.end(msg2);
                        let obj = {"admin":username,"password1":password1,"password2":password2}
                        arrList.push(obj)
                        const str = JSON.stringify(arrList)
                        console.log(str);
                        fs.writeFile('./login.json', str, 'utf-8', function (err, data) {
                           
                        })
                    }
                })
            })
        }
    }
}).listen(3000, '127.0.0.1')